# -*- coding: utf-8 -*-
"""
Created on
@Time: 2024/12/23 11:27
@Author: Mr.Z
@contact: <QQ:40061980>
@contact: bob@pheks.com
@File: infoPage.py
@IDE: PyCharm
@Python Version：
"""
import os
from datetime import datetime

from PySide6.QtWidgets import QWidget, QVBoxLayout, QPlainTextEdit

from utils.log_recorder import setup_logger as logger


class InfoPage(QWidget):
    def __init__(self, log_text_edit):
        super().__init__()

        # 获取当前日期
        current_date = datetime.now().strftime('%Y-%m-%d')
        self.log_file_name = f"{current_date}.log"
        self.log_file_path = os.path.join("./logs", self.log_file_name)

        # 创建主布局
        main_layout = QVBoxLayout()

        # 创建日志文本编辑框
        self.log_text_edit = QPlainTextEdit()
        self.log_text_edit.setReadOnly(True)  # 设置为只读

        # 加载日志文件内容
        self.load_log()

        main_layout.addWidget(self.log_text_edit)

        # 设置中心部件的布局
        self.setLayout(main_layout)

    def load_log(self):
        self.log_text_edit.clear()  # 清空文本编辑框
        self.log_text_edit.appendPlainText("-"*40 + "\n")  # 分割线

        # 获取当前日期，和日志文件名中的日期格式一致
        current_date = datetime.now().strftime('%Y%m%d')

        # 遍历logs目录，查找文件名包含当前日期的文件
        if os.path.exists("./logs"):
            for file_name in os.listdir("./logs"):
                if current_date in file_name:
                    file_path = os.path.join("./logs", file_name)
                    try:
                        with open(file_path, "r", encoding="utf-8") as log_file:
                            log_content = log_file.read()
                            # self.log_text_edit.appendPlainText(f"文件 {file_name} 的内容:\n")
                            self.log_text_edit.appendPlainText(log_content)
                            self.log_text_edit.appendPlainText("\n" + "-"*40 + "\n")  # 分割线
                    except Exception as e:
                        self.log_text_edit.appendPlainText(f"读取文件 {file_name} 时出错: {str(e)}\n")
                        logger().error(f"[infoPage-load_log]{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: 读取文件 {file_name} 时出错: {str(e)}")
        else:
            self.log_text_edit.appendPlainText(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: 未找到logs目录")
            logger().warning(f"[infoPage-load_log]{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: 未找到logs目录")


# 示例用法
if __name__ == "__main__":
    from PySide6.QtWidgets import QApplication

    app = QApplication([])
    info_page = InfoPage(None)
    info_page.show()
    app.exec()
